package com.lzy.cloud.ticket.admission.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 2016-12-06 http请求调用
 * @author tengyong
 *
 */
@Slf4j
public class SendUtil {
	/**
	 * get连接请求
	 * 
	 * @param url 完整url
	 * @return
	 */
	public static String sendGetConn(String url, Map<String, Object> paramsMap){
		
		try {
			
			// 获取签名参数字符串
//			String params = createUrlStr(paramsMap, apiKey, secretKey);
//			if(params == null){
//				System.out.println("***********  error message  ************");
//				System.out.println("创建签名参数字符串失败。");
//				return null;
//			}
			
			String params = "";
			for(Map.Entry<String, Object> entry : paramsMap.entrySet()){
				params += (entry.getKey() + "=" + entry.getValue() + "&");
			}
			
			if(!params.equals("")){
				url += ("?" + params.substring(0, params.length() - 1));
			}
			
			System.out.println(url);

			URL getUrl  = new URL(url);
			
			HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
			// 编码
			connection.setRequestProperty("contentType", "UTF-8");
			// 请求超时，10秒
			connection.setConnectTimeout(10 * 1000);
			// 
			connection.setRequestMethod("GET");
			
			connection.connect();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			
			String lines;
	        while ((lines = reader.readLine()) != null) {
	            System.out.println(lines);
	        }
	        reader.close();
	        connection.disconnect();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * post连接请求
	 * 
	 * @param url 完整的url
	 * @return
	 */
	public static String sendPostConn(String url, Map<String, Object> paramsMap, String apiKey, String secretKey){
		try {
			
			// 获取签名参数字符串
			String params = createUrlStr(paramsMap, apiKey, secretKey);
			if(params == null){
				log.error("创建签名参数字符串失败.");
				return null;
			}

			// 发送请求
			URL postUrl  = new URL(url);
			HttpURLConnection connection = (HttpURLConnection)postUrl.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("contentType", "UTF-8");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json");
			
			connection.connect();
			
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); 

			log.info(params);
			out.write(params);
			
			out.flush();
			out.close();
			
			// 获取接口返回结果
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			
			StringBuffer result = new StringBuffer("");
			String line;
			while ((line = reader.readLine()) != null) {
	            result.append(line);
	        }
			reader.close();
	        connection.disconnect();
			
	        // 返回结果
	        System.out.println("获取返回结果成功：\r\n" + result.toString());
	        return result.toString();
		} catch (MalformedURLException e) {
			log.error("请确认请求的URL地址是否正确");
			e.printStackTrace();
		} catch (ProtocolException e) {
			log.error("设置请求类型错误，确认是否是POST请求？");
			e.printStackTrace();
		} catch (IOException e) {
			log.error("访问地址不可用.");
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 创建签名后的url
	 * 
	 * @param paramsMap
	 * @param apiKey
	 * @param secretKey
	 * @return
	 */
	private static String createUrlStr(Map<String, Object> paramsMap, String apiKey, String secretKey){


		// 组织数据格式，获取签名
		Map<String, Object> temp = new HashMap<String, Object>();
		
		if(apiKey != null && !"".equals(apiKey)){
			temp.put("apiKey", apiKey);
		}else{
			log.error("apiKey 不能为空.");
			return null;
		}
		
		if(secretKey != null && !"".equals(secretKey)){
			
		}else{
			log.error("密钥[secretKey]不能为空.");
			return null;
		}
		
		temp.put("timestamp", DateUtil.format(new Date()));
		
		if(paramsMap != null){
			temp.put("data", JSON.toJSON(paramsMap));
		}else{
			temp.put("data", JSON.toJSON(new HashMap<String, Object>()));
		}
		
		String params = null;

		
		try {
			// 签名后的url
			params = SigntrueUtil.getSignature(JSONObject.parseObject(JSONObject.toJSONString(temp)), secretKey);
			log.info("***********  获取签名成功   ************\"");
			System.out.println(params);
			System.out.println();
			temp.put("sign", params);
		} catch (Exception e) {
			log.error("***********  获取签名异常   ************");
			System.out.println();
			e.printStackTrace();
		}
		
		return JSONObject.toJSONString(temp);
	}
	
	
}
